package com.fengye.lock.db.controller;

import com.fengye.lock.db.dto.UserAccountDTO;
import com.fengye.lock.db.response.BaseResponse;
import com.fengye.lock.db.response.StatusCode;
import com.fengye.lock.db.service.DatabaseLockService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 *
 * @author sky
 * @date 2021年06月11日 10:33 上午
 */
@RestController
@RequestMapping("/money")
@Slf4j
public class DatabaseLockController {


    @Autowired
    DatabaseLockService databaseLockService;

    @PostMapping("/take")
    public BaseResponse takeMoney(@RequestBody @Validated UserAccountDTO dto, BindingResult result) {
        if (dto.getAmount() == null || dto.getUserId() == null) {
            return new BaseResponse(StatusCode.InvalidParams);
        }

        BaseResponse response = new BaseResponse(StatusCode.Success);

        try {
            databaseLockService.takeMoney(dto);
        } catch (Exception e) {
            response = new BaseResponse(StatusCode.Fail.getCode(), e.getMessage());
        }
        return response;

    }

    @PostMapping("/version/take")
    public BaseResponse takeMoneyWithVersion(@RequestBody @Validated UserAccountDTO dto, BindingResult result) {
        if (dto.getAmount() == null || dto.getUserId() == null) {
            return new BaseResponse(StatusCode.InvalidParams);
        }

        BaseResponse response = new BaseResponse(StatusCode.Success);

        try {
            databaseLockService.takeMoneyWithVersion(dto);
        } catch (Exception e) {
            response = new BaseResponse(StatusCode.Fail.getCode(), e.getMessage());
        }
        return response;

    }

    @PostMapping("/negative/take")
    public BaseResponse takeMoneyWithNegativeLock(@RequestBody @Validated UserAccountDTO dto, BindingResult result) {
        if (dto.getAmount() == null || dto.getUserId() == null) {
            return new BaseResponse(StatusCode.InvalidParams);
        }

        BaseResponse response = new BaseResponse(StatusCode.Success);

        try {
            databaseLockService.takeMoneyWithNegativeLock(dto);
        } catch (Exception e) {
            response = new BaseResponse(StatusCode.Fail.getCode(), e.getMessage());
        }
        return response;

    }
}
